import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Row, Col, Card, Icon, Button, Dropdown, Popconfirm, message, Divider, Form, Select, Cascader, Input} from "antd";
import StandardTable from '../../../components/StandardTable';
import Upload from "../../../components/Upload";
import RegionalSelection from "../../Form/RegionalSelection";
import styles from '../../Pbulic.less';
import Authorized from '../../../utils/Authorized';


const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(({ equipment_integrated, global, loading }) => ({
  resdata: equipment_integrated.resdata,
  loading: equipment_integrated.loading,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class ListTable extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],
      formValues: {},
    };
  }


  componentWillReceiveProps(nextProps) {
    // 外层发起刷新数据请求
    if (nextProps.isReloadList === true && this.props.isReloadList === false) {
      const { pageSize, formValues, currentPage } = this.state;
      if(nextProps.detailId===0){
        this.getDataList({},pageSize,1);
      }else{
        this.getDataList(formValues,pageSize,currentPage);
      }
      this.props.sotpReloadList();
    }
  }


  componentDidMount() {
    const { pageSize } = this.state;
    const { pagesquery,dispatch } = this.props;

    // 列表
    this.getDataList(pagesquery,pageSize,1);
  }

  // 安装点位事件
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }

  }





  getDataList(params,pageSize,currentPage) {
    const { dispatch } = this.props;

    dispatch({
      type: 'equipment_integrated/fetch_integrated_list',
      payload: {
        pageSize,
        currentPage,
        // ...pagesquery,
        ...params,
        region:undefined,
      },
    });
  }

  // 分页、排序、筛选变化时触发
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      // currentPage: pagination.current,
      // pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };

    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    this.setState({
      currentPage:pagination.current
    },()=>{
      this.getDataList(params,pageSize,pagination.current);
    })

  };

  // 重置表单
  handleFormReset = () => {
    const { form } = this.props;
    const {pageSize,currentPage} = this.state;
    //form.resetFields();
    form.setFieldsValue({
      devName:undefined,
      devType:undefined,
      status:"全部",
      maintenanceId:undefined,
      region:{districtId:[],pointId:0},
      adminUserId:undefined
    })
    this.setState({
      formValues: {},
    });
    this.getDataList({},pageSize,1);
  };


  // 表格复选框选中
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows.map(item => item.devId),
    });
  };

  // 表单搜索
  handleSearchSubmit = e => {
    e.preventDefault();

    const { form } = this.props;
    const { pageSize } = this.state;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      // if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
      //     fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
      //     fieldsValue.pointId = fieldsValue.region.pointId;
      // }
      if(fieldsValue.region && fieldsValue.region.districtId.length>0){
        fieldsValue.districtId = fieldsValue.region.districtId[fieldsValue.region.districtId.length - 1];
      }
      if(fieldsValue.region && fieldsValue.region.pointId!==0 && fieldsValue.region.districtId.length>0){
        fieldsValue.pointId = fieldsValue.region.pointId;
      }


      if(fieldsValue.status=="全部"){
        fieldsValue.status=undefined;
      }


      this.setState({
        formValues: fieldsValue,
      });

      this.getDataList(fieldsValue,pageSize,1);
    });
  };




  // 1白名单、2报废、3批量删除、4导出
  handleActionList = (type,id) => {
    const { dispatch } = this.props;
    const { selectedRows,formValues, pageSize, currentPage } = this.state;
    if(!id && !selectedRows) return;
    const devIds= id ? [id] : selectedRows;

    switch (type) {
      case '2':
        dispatch({
          type: 'equipment_integrated/action_equipment_scrap',
          payload: {
            devIds,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选设备已报废")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });
        break;
      case '3':
        dispatch({
          type: 'equipment_integrated/action_equipment_del',
          payload: {
            devIds,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("所选设备已删除")
        }).then(()=>{
          this.getDataList(formValues,pageSize,currentPage);
        });
        break;
      case '4':
        dispatch({
          type: 'equipment_integrated/action_equipment_export',
          payload: {
            devIds,
          },
        }).then(()=>{
          this.setState({
            selectedRows: [],
          });
        }).then(()=>{
          message.success("设备文件导出成功")
        });
        break;

      default:

        break;
    }
  };

  // 批量导入
  handleBatchImport = info => {
    let fileList = info.fileList;
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    if (info.file.status == "done") {
      fileList = fileList.map(item => {
        if (item.response && item.response.error_no != "0") {
          item.status = "error";
        }
        return item;
      });


      if(info.file && info.file.response && info.file.response.data && info.file.response.data.token){
        dispatch({
          type: 'equipment_integrated/action_equipment_import',
          payload: {
            file_url:info.file.response.data.token,
          },
        }).then(()=>{
          message.success("文件导入成功")
        }).then(()=>{
          this.getDataList(formValues,pageSize,1);
        });
      }

    }


  };

  // 新增model传导-------------------
  handleAddModel = (e) =>{
    this.props.addModelCallBack(e);
  }
  // 详情model传导
  handleDetailModel= (detailInfoId,detailInfoName) =>{
    // this.props.detailModelCallBack(id,name);
    const { formValues, currentPage} = this.state;
    router.push({ pathname:`/equipment/device/${detailInfoId}/info`,  query: { ...formValues, currentPage} });

  }
  // 添加白名单model传导
  handleWiteListModel= (ids) =>{
    this.props.witeListModelCallBack(ids);
  }

  // 取消白名单
  handleWiteListCancel= (devId) =>{
    const { dispatch } = this.props;
    const { formValues,pageSize } = this.state;

    devId && dispatch({
      type: 'equipment_integrated/action_equipment_witelist_cancel',
      payload: {
        devIds:devId,
      },
    }).then(()=>{
      message.success("白名单已取消")
    }).then(()=>{
      this.getDataList(formValues,pageSize,1);
    });

  }

  // 搜索内容
  renderSearchForm() {
    const { form, dictionaries, selectSource, pagesquery } = this.props;
    const { getFieldDecorator } = form;

    // console.log('pointData',selectSource.pointData)

    return (
      <Form onSubmit={this.handleSearchSubmit} >
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="设备名称">
              {getFieldDecorator('devName',{
                initialValue: pagesquery && pagesquery.devName ? pagesquery.devName : undefined,
              })(<Input placeholder="请输入设备名称" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="设备类型">
              {getFieldDecorator('devType',{
                initialValue: pagesquery && pagesquery.devType ? pagesquery.devType : undefined,
              })(
                <Select  allowClear={true} placeholder="请选择设备类型" style={{ width: '100%' }} >
                  {dictionaries.deviceType && dictionaries.deviceType.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="当前状态">
              {getFieldDecorator('status',{
                 initialValue: pagesquery && pagesquery.status ? pagesquery.status : "全部",
              })(
                <Select   style={{ width: '100%' }}>
                  <Option key={"全部"} value={null}>全部</Option>
                  {dictionaries.deviceStatus && dictionaries.deviceStatus.map(item => (
                    <Option key={item.value} value={item.value}>{item.label}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <FormItem label="维保单位">
              {getFieldDecorator('maintenanceId',{
                initialValue: pagesquery && pagesquery.maintenanceId ? pagesquery.maintenanceId : undefined,
              })(
                <Select  allowClear={true} placeholder="请选择维保单位"   style={{ width: '100%' }}>
                  {selectSource.maintenance && selectSource.maintenance.map(item => (
                    <Option key={item.maintenanceId} value={item.maintenanceId}>{item.maintenanceName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
        </Row>

        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={12} sm={24}>
            <FormItem label="区域点位">
              {getFieldDecorator('region',{
                 initialValue: pagesquery && pagesquery.region ? pagesquery.region : {districtId:[],pointId:0},
              })(
                <RegionalSelection
                  districtData={selectSource.districtData}
                  pointData={selectSource.pointData}
                  onChange={this.handleSearchDistrict}
                />
              )}
            </FormItem>

          </Col>
          <Col md={6} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;&nbsp;管理员">
              {getFieldDecorator('adminUserId',{
                initialValue: pagesquery && pagesquery.adminUserId ? pagesquery.adminUserId : undefined,
              })(
                <Select  allowClear={true} placeholder="请选择管理员"   style={{ width: '100%' }}>
                  {selectSource.adminUser && selectSource.adminUser.map(item => (
                    <Option key={item.userId} value={item.userId}>{item.realName}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={6} sm={24}>
            <div style={{ float: 'right', marginBottom: 24 }}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </div>
          </Col>

        </Row>
      </Form>
    );
  }


  render() {

    const { resdata, loading, dictionaries } = this.props;
    const { selectedRows } = this.state;
    const deviceStatus = dictionaries.deviceStatus && dictionaries.deviceStatus.length>0
      ? dictionaries.deviceStatus.map(item=>item.label)
      :[];



    const columns = [
      {
        title: '序号',
        dataIndex: 'no',
        width: 100,
        fixed: 'left',
        render: (text, row, index)=> (
          <span>{index+1}</span>
        ),
      },
      {
        title: '设备编号',
        width: 100,
        dataIndex: 'devCode',
      },
      {
        title: '设备名称',
        width: 200,
        dataIndex: 'devName',
      },
      {
        title: '规格型号',
        width: 100,
        dataIndex: 'devModel',
      },
      {
        title: '设备状态',
        width: 100,
        dataIndex: 'status',
        render: (text)=> (
          <span>{deviceStatus[parseInt(text)-1]}</span>
        ),
      },
      {
        title: '品牌',
        width: 150,
        dataIndex: 'trademark',
      },
      {
        title: '供应商',
        width: 150,
        dataIndex: 'supplier',
      },
      {
        title: '维保单位',
        width: 200,
        dataIndex: 'maintenanceName',
      },
      {
        title: '设备管理员',
        width: 200,
        dataIndex: 'adminUserName',
      },

      {
        title: '操作',
        width: 300,
        fixed: 'right',
        render: (text, row, index) => (
          <Fragment>
            <Authorized authority={'10003'} >
              <a onClick={() => this.handleDetailModel(row.devId, row.devName)}>详情</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10004'} >
              <a onClick={() => this.handleAddModel(row.devId)}>修改</a>
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10005'} >
              {row.status!=="09" && <a onClick={() => this.handleWiteListModel([row.devId])}>加入白名单</a>}
              {row.status=="09" && <Popconfirm title="是否确定要取消白名单?" onConfirm={() => this.handleWiteListCancel([row.devId])}  okText="是" cancelText="否"><a >取消白名单</a></Popconfirm>}
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10006'} >
              {row.status!=="07" && <Popconfirm title="是否确定要报废?" onConfirm={() => this.handleActionList("2",row.devId)}  okText="是" cancelText="否">
                <a >报废</a>
              </Popconfirm>}
              {row.status=="07" && <span style={{color:'#ccc'}}>报废</span>}
              <Divider type="vertical" />
            </Authorized>
            <Authorized authority={'10007'} >
              <Popconfirm title="是否确定要删除?" onConfirm={() => this.handleActionList("3",row.devId)}  okText="是" cancelText="否">
                <a >删除</a>
              </Popconfirm>
            </Authorized>
          </Fragment>
        ),
      },
    ];




    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderSearchForm()}</div>
          <div className={styles.tableListOperator}>
            <Authorized authority={'10002'} >
              <Button icon="plus" type="primary"  onClick={() => this.handleAddModel(0)}>
                新建
              </Button>
            </Authorized>

            {/*<Authorized authority={'10008'} >*/}
            {/*<Upload showUploadList={false} onChange={this.handleBatchImport}>*/}
              {/*<Button icon="plus" type="primary" >*/}
                {/*批量导入*/}
              {/*</Button>*/}
            {/*</Upload>*/}
            {/*</Authorized>*/}

            <Authorized authority={'10009'} >
            <Popconfirm title="是否确定要批量删除?" onConfirm={() => this.handleActionList("3")}  okText="是" cancelText="否">
              <Button icon="minus" type="default" disabled={selectedRows.length > 0 ? false : true}>
                批量删除
              </Button>
            </Popconfirm>
            </Authorized>

            <Authorized authority={'10005'} >
            <Button type="default" onClick={() => this.handleWiteListModel(selectedRows)}  disabled={selectedRows.length > 0 ? false : true}>
              加入白名单
            </Button>
            </Authorized>

            <Authorized authority={'10006'} >
            <Popconfirm title="是否确定要报废?" onConfirm={() => this.handleActionList("2")}  okText="是" cancelText="否">
              <Button type="default"  disabled={selectedRows.length > 0 ? false : true}>
                报废
              </Button>
            </Popconfirm>
            </Authorized>

            <Authorized authority={'10010'} >
            {/*<Button type="default" onClick={() => this.handleActionList("4")} disabled={selectedRows.length > 0 ? false : true}>*/}
              {/*导出*/}
            {/*</Button>*/}
            </Authorized>

          </div>
          <StandardTable
            selectedRows={selectedRows}
            rowKey="devId"
            scroll={{ x: 1500 }}
            loading={loading.integrated_list}
            data={resdata}
            columns={columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
      </Card>

    );
  }
}
